package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winning.pmph.entity.ReleasedKnowledge;
import com.winning.pmph.service.ReleasedKnowledgeService;
import com.winning.pmph.service.RestHighLevelService;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.Const;
import com.winning.pmph.vo.EsKnowledge;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(value = "知识资源管理/知识搜索")
@RestController
@RequestMapping("/pmph/action/esKnowledge")
public class EsKnowledgeCtrl {

    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private RestHighLevelService restHighLevelService;

    /**
     * 知识搜索page;
     */
    @ApiOperation(value = "selectPage", notes = "搜索页面")
    @GetMapping("selectPage")
    public Page<EsKnowledge> selectPage(String keywords, String knowledgeLibId, int currentPage, int pageSize) {
        Page<EsKnowledge> result = new Page<>(currentPage, pageSize);
        result.setRecords(new ArrayList<>());
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder nameFuzzyQuery = QueryBuilders.fuzzyQuery("name", keywords);
        MatchQueryBuilder contentMatchQuery = QueryBuilders.matchQuery("content", keywords);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(knowledgeLibId)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("knowledgeLibId", knowledgeLibId));
        }
        boolQueryBuilder.should(nameFuzzyQuery)
                .should(contentMatchQuery);
        sourceBuilder.query(boolQueryBuilder).from((currentPage - 1) * pageSize).size(pageSize);
        searchRequest.indices(Const.ES_KNOWLEDGE_INDEX).source(sourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
            result.setTotal(searchResponse.getHits().getTotalHits());
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                EsKnowledge esKnowledge = JSON.parseObject(hit.getSourceAsString(), EsKnowledge.class);
                result.getRecords().add(esKnowledge);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    @ApiOperation(value = "initEsKnowledge", notes = "initEsKnowledge")
    @GetMapping("/initEsKnowledge")
    public void initEsKnowledge() {
        List<ReleasedKnowledge> list = ApplicationContextUtil
                .getBean(ReleasedKnowledgeService.class)
                .list();
        for (ReleasedKnowledge knowledge : list) {
            EsKnowledge esKnowledge = EsKnowledge.parse2EsKnowledge(knowledge);
            restHighLevelService.insertEsKnowledge(esKnowledge);
        }
    }
}
